package cn.signalpha.modules.social.service;

import cn.hutool.core.date.DateUtil;
import cn.signalpha.common.cache.ConfigCache;
import cn.signalpha.common.cache.ConfigKeys;
import cn.signalpha.common.dto.ConfigDTO;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.BeanUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.com.dto.UserLevelLogDTO;
import cn.signalpha.modules.com.entity.enums.LevelSourceEnum;
import cn.signalpha.modules.com.service.UserLevelLogService;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.social.dto.TopicDTO;
import cn.signalpha.modules.social.entity.Topic;
import cn.signalpha.modules.social.mapper.TopicMapper;
import cn.signalpha.modules.social.vo.TopicVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 服务类
 *
 * @author signalpha
 */
@Service
@AllArgsConstructor
public class TopicService extends ServiceImpl<TopicMapper, Topic> {

	private final UserService userService;
	private final UserLevelLogService userLevelLogService;

	/**
	 * 自定义分页
	 */
    public IPage<TopicVO> selectTopicPage(IPage<TopicVO> page, Map<String, Object> params) {
        return page.setRecords(baseMapper.selectTopicPage(page, params));
    }

	/**
	 * 自定义Wrapper
	 */
	public QueryWrapper<Topic> selectTopicWrapper(Map<String, Object> params) {
		QueryWrapper<Topic> wrapper = Wrappers.query();
		wrapper.lambda().in(ObjectUtil.isNotEmpty(params.get("ids")), Topic::getId, Func.toLongList(String.valueOf(params.get("ids"))));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("userId")), Topic::getUserId, params.get("userId"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("status")), Topic::getStatus, params.get("status"));
		wrapper.lambda().eq(ObjectUtil.isNotEmpty(params.get("isShow")), Topic::getIsShow, params.get("isShow"));
		wrapper.lambda().ge(ObjectUtil.isNotEmpty(params.get("createTimeBegin")), Topic::getCreateTime, params.get("createTimeBegin"));
		wrapper.lambda().le(ObjectUtil.isNotEmpty(params.get("createTimeEnd")), Topic::getCreateTime, params.get("createTimeEnd"));
		wrapper.lambda().orderByDesc(Topic::getId);
		return wrapper;
	}

	/**
	 * 数量统计
	 */
	public long countByParams(Map<String, Object> params) {
		return count(selectTopicWrapper(params));
	}

	/**
	 * 保存主题
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean saveTopic(TopicDTO.SaveDTO topicDTO) {
		ConfigDTO.SocialDTO config = ConfigCache.getObject(ConfigKeys.SOCIAL, ConfigDTO.SocialDTO.class);

		Topic topic = Objects.requireNonNull(BeanUtil.copy(topicDTO, Topic.class));
		topic.setIsShow(1);
		topic.setStatus(config.getIsTopicAudit() == 1 ? 0 : 1);
		topic.setTarget(JsonUtil.toJson(topicDTO.getGoodsList()));
		topic.setCreateTime(new Date());
		baseMapper.insert(topic);

		if(topic.getStatus() == 1){
			Date now = new Date();
			Date beginTime = DateUtil.beginOfDay(now);
			long count = userLevelLogService.countByParams(Kv.create().set("sourceType", "social").set("createTimeBegin", beginTime).set("createTimeEnd", now));
			if(config.getExpNum() > count){
				userService.updateUserExp(UserLevelLogDTO.builder()
					.userId(topic.getUserId())
					.amount(config.getExp())
					.sourceId(topic.getId().toString())
					.sourceType(LevelSourceEnum.SOCIAL.getType())
					.remark(LevelSourceEnum.SOCIAL.getName())
					.build());
			}
		}
		return true;
	}

	/**
	 * 编辑主题
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean updateTopic(TopicDTO.UpdateDTO topicDTO) {
		ConfigDTO.SocialDTO config = ConfigCache.getObject(ConfigKeys.SOCIAL, ConfigDTO.SocialDTO.class);

		Topic topic = Objects.requireNonNull(BeanUtil.copy(topicDTO, Topic.class));
		topic.setTarget(JsonUtil.toJson(topicDTO.getGoodsList()));
		topic.setStatus(config.getIsTopicAudit() == 1 ? 0 : 1);

		baseMapper.updateById(topic);
		return true;
	}


}

